import React, { useState } from 'react';
import '../style/issue.css';
import axios from '../../utils/http';
import { useNavigate } from "react-router-dom"

export default function Issue() {
    const imageUrl = localStorage.getItem('image');
    const userid = JSON.parse(localStorage.getItem('user'))[0]._id;
    const navigate = useNavigate()

    const [form, setForm] = useState({
        filePath: imageUrl,
        describe: '',
        userId: userid
    });

    const handleIssue = async () => {
        const res = await axios.post('/yzh/uploadVoice', form);
        if (res.code === 200) {
            console.log('发布成功');
            navigate("/")
        }
    };

    // 判断文件类型
    const isImage = (url) => {
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif'];
        return imageExtensions.some(ext => url.toLowerCase().endsWith(ext));
    };

    const isVideo = (url) => {
        const videoExtensions = ['.mp4', '.webm', '.ogg'];
        return videoExtensions.some(ext => url.toLowerCase().endsWith(ext));
    };

    return (
        <div className='issue-box'>
            <div className='video'>
                {isImage(imageUrl) && <img src={imageUrl || ''} alt="Uploaded content" />}
                {isVideo(imageUrl) && <video src={imageUrl || ''} controls />}
            </div>

            <div>
                <p style={{ fontSize: '2rem', color: 'white' }}>描述内容：</p>
                <textarea
                    value={form.describe}
                    onChange={(e) => setForm({ ...form, describe: e.target.value })}
                    style={{ width: '100%', height: '20rem', backgroundColor: 'black', border: 'none', color: 'white' }}
                    placeholder='请输入内容'
                />
            </div>
            <p style={{ width: '100%', textAlign: 'center' }}>
                <button
                    onClick={handleIssue}
                    style={{
                        backgroundColor: '#ff3957',
                        color: 'white',
                        width: '20rem',
                        height: '4rem',
                        borderRadius: '.5rem'
                    }}
                >
                    发布
                </button>
            </p>
        </div>
    );
}